<template>
    <div>
        <!-- 面包屑区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>活动管理</el-breadcrumb-item>
            <el-breadcrumb-item>活动列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片容器 -->
        <el-card >
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入姓名" v-model="queryInfo.query" clearable @clear="getUsersList">
                      <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- b:用户列表 -->
            <el-table  :data="usersList" border stripe>
              <el-table-column
               type="index"
                label="#">
              </el-table-column>
              <el-table-column
                prop="username"
                label="姓名">
              </el-table-column>
              <el-table-column
                prop="email"
                label="邮箱">
              </el-table-column>
              <el-table-column
                prop="mobile"
                label="电话">
              </el-table-column>
              <el-table-column
                label="角色">
                <template slot-scope="scope">
                  <el-switch
                  v-model="scope.row.mg_state" @change="changeUserState(scope.row)">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column width="180px"
                label="操作">
                <template slot-scope="scope">
                  <el-button :id="scope.row"  type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserInfo(scope.row.id)"></el-button>
                  <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <!-- c:分页跳转实现 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pagenum"
              :page-sizes="[1, 2, 3, 10]"
              :page-size="queryInfo.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </el-card>
        <!-- e:添加用户对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="addDialogVisible"
          width="50%"
          @close="closeAddDialog">
          <!-- 内容区域 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <!-- 底部按钮区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmAdd">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户对话框 -->
        <el-dialog
          title="修改用户"
          :visible.sync="editDialogVisible"
          width="30%"
          @close="editDialogClosed">
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" >
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmEditInfo">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="setRolseDialogVisible"
          width="50%"
          @close="setRolseDialogClose"
         >
         <div>
           <p>当前的用户:{{roleInfo.username}}</p>
           <p>当前的角色:{{roleInfo.role_name}}</p>
           <p>分配新角色：
              <el-select v-model="selectedRoleId" placeholder="请选择">
                <el-option
                  v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
           </p>
         </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRolseDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmSetRole">确 定</el-button>
          </span>
        </el-dialog>
    </div>

</template>

<script>
// z:实现角色分配弹框的展示和角色列表获取
// y:分配角色功能实现
export default {
    // 数据
    data() {
        // 验证邮箱合法性
        var checkEmail = (rule, value, callback) => {
          const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          if (regEmail.test(value)) {
            // 邮箱合法
            return callback()
          }
          // 邮箱不合法
          callback(new Error('输入的邮箱不合法'))
        }
        // 验证手机号合法性
        var checkMobile = (rule, value, callback) => {
          const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
          if (regMobile.test(value)) {
            // 邮箱合法
            return callback()
          }
          // 邮箱不合法
          callback(new Error('输入的手机号不合法'))
        }
        return {
            // 请求参数
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 2
            },
            usersList: [],
            total: 0,
            addDialogVisible: false,
            // 修改用户对话框flag
            editDialogVisible: false,
            addForm: {
              username: '',
              password: '',
              email: '',
              mobile: ''
            },
            addFormRules: {
              username: [
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 3, max: 10, message: '长度在3-10个字符', trigger: 'blur' }
              ],
              password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 6, max: 15, message: '长度在6-15个字符', trigger: 'blur' }
              ],
              email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { validator: checkEmail, trigger: 'blur' }
              ],
              mobile: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator: checkMobile, trigger: 'blur' }
              ]
            },
            editForm: {},
            editFormRules: {
              email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { validator: checkEmail, trigger: 'blur' }
              ],
              mobile: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator: checkMobile, trigger: 'blur' }
              ]
            },
            setRolseDialogVisible: false,
            // 当前用户的角色信息
            roleInfo: {},
            // 角色列表
            rolesList: [],
            // 选中角色的id
            selectedRoleId: ''
        }
    },
    // created生命周期
    created () {
        // a:获取用户数据列表
        this.getUsersList()
    },
    // 方法
    methods: {
        async getUsersList() {
            // a1：调用接口获取数据
            const { data: res } = await this.$html.get('/users', { params: this.queryInfo })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.usersList = res.data.users
            this.total = res.data.total
        },
        // 页码尺寸变化监听事件
        handleSizeChange(pageSize) {
          this.queryInfo.pagesize = pageSize
          this.getUsersList()
        },
        // 当前页变化事件监听
        handleCurrentChange(currentPage) {
          this.queryInfo.pagenum = currentPage
          this.getUsersList()
        },
        // d:使用用户角色修改
        async changeUserState(userInfo) {
          // d2：调用接口修改用户角色
          const { data: res } = await this.$html.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
         if (res.meta.status !== 200) {
           userInfo.mg_state = !userInfo.mg_state
           return this.$message.error('修改用户角色失败')
         }
         this.$message.success('修改用户角色成功')
        },
        closeAddDialog () {
          this.$refs.addFormRef.resetFields()
        },
        confirmAdd() {
          this.$refs.addFormRef.validate(async valid => {
           if (!valid) return false
           // e: 验证成功，实现添加
           // e1:调用添加用户的接口
          const { data: res } = await this.$html.post('users', this.addForm)
          console.log(res)
          if (res.meta.status !== 201) {
            return this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功')
          // e2:关闭弹框，重新刷新数据
          this.addDialogVisible = false
          this.getUsersList()
          })
        },
        async editUser(id) {
          // f:获取被编辑的用户信息
          // f1：调用接口获取用户信息
          const { data: res } = await this.$html.get('users/' + id)
          if (res.meta.status !== 200) {
            return this.$message.error('获取用户信息失败')
          }
          // f2：将获取的信息赋值给data中的变量
          this.editForm = res.data
          this.editDialogVisible = true
        },
        // g：重置修改用户信息弹框
        editDialogClosed() {
          this.$refs.editFormRef.resetFields()
        },
        // 修改信息的预校验
        confirmEditInfo() {
          this.$refs.editFormRef.validate(async valid => {
            // 如果预校验失败，终止程序
            if (!valid) return false
            // 发起修改用户的信息的网络请求
            const { data: res } = await this.$html.put('users/' + this.editForm.id, {
              email: this.editForm.email,
              mobile: this.editForm.mobile
            })
           if (res.meta.status !== 200) return this.$message.error('修改用户信息失败！')
           this.editDialogVisible = false
           this.getUsersList()
           this.$message.success('修改信息成功！')
          })
        },
        // h：实现删除用户操作
        async removeUserInfo(id) {
          // h1：删除前弹出确认提示框
         const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).catch(err => err)
          console.log(confirmResult)
          if (confirmResult !== 'confirm') return this.$message.info('已取消删除操作')
          // 如果点击确定进行删除操作
          const { data: res } = await this.$html.delete('users/' + id)
          if (res.meta.status !== 200) {
            return this.$message.error('删除用户失败')
          }
          // 删除用户成功
          this.$message.success('删除用户成功!')
          this.getUsersList()
        },
        // z1:分配权限弹框点击事件监听
        async setRole(roleInfo) {
          // z2:修改内容区域
          this.roleInfo = roleInfo
          // z3：通过接口获取角色列表，用来填充下拉框
          const { data: res } = await this.$html.get('roles')
          if (res.meta.status !== 200) {
            return false
          }
          // 获取列表数据成功
         this.rolesList = res.data
          this.setRolseDialogVisible = true
        },

        // y1：对分配权限单框确定按钮进行监听
        async confirmSetRole() {
          // y2：判断用户是否选择了角色
          if (!this.selectedRoleId) {
            return this.$message.error('请选择新的角色')
          }
          // y3:获取调用分配用户角色需要的参数
          const { data: res } = await this.$html.put(`users/${this.roleInfo.id}/role`, {
            rid: this.selectedRoleId
          })
          if (res.meta.status !== 200) {
            return this.$message.error('角色设置失败')
          }
          // 分配角色成功
          this.$message.success('设置角色成功！')
          this.getUsersList()
          this.setRolseDialogVisible = false
        },
        // y4:对关闭分配角色弹框进行监听
        setRolseDialogClose() {
          this.selectedRoleId = ''
          this.roleInfo = {}
        }
    }

}
</script>

<style lang="less" scoped>

</style>